package com.honghu.paylibrary.utils;

import android.text.TextUtils;
import android.util.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 创建日期 2020/4/24
 * 描述：
 */
public class MD5Util {
    public MD5Util() {
    }

    public static String encode(String value) {
        if (TextUtils.isEmpty(value)) {
            return "";
        } else {
            String hs = "";

            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(value.getBytes());
                byte[] ctext = md.digest();
                String stmp = "";

                for(int n = 0; n < ctext.length; ++n) {
                    stmp = Integer.toHexString(ctext[n] & 255);
                    if (stmp.length() == 1) {
                        hs = hs + "0" + stmp;
                    } else {
                        hs = hs + stmp;
                    }
                }
            } catch (Exception var6) {
                var6.printStackTrace();
            }

            return hs;
        }
    }

    public static String encodeFile(File file) {
        if (file == null) {
            return "";
        } else {
            try {
                FileInputStream fis = new FileInputStream(file);
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] buffer = new byte[1024];
                boolean var4 = true;

                int length;
                while((length = fis.read(buffer, 0, 1024)) != -1) {
                    md.update(buffer, 0, length);
                }

                fis.close();
                BigInteger bigInt = new BigInteger(1, md.digest());
                return bigInt.toString(16);
            } catch (Exception var6) {
                var6.printStackTrace();
                return "";
            }
        }
    }


    /**
     *
     * @Title: MD5Utils.java
     * @Description: 对字符串进行md5加密
     */
    public static String getMD5Str(String strValue) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String newstr = Base64.encodeToString(md5.digest(strValue.getBytes()), Base64.DEFAULT);
        return newstr;
    }

}
